const fs = require("fs");
const path = require("path");

const gifify = require("gifify");

const options = {
  resize: "441:235",
  colors: 255,
  fps: 60,
  speed: 0.5,
};

async function convertFile(input) {
  return new Promise((resolve, reject) => {
    const inputFileInfo = fs.statSync(input);
    const inputDir = path.dirname(input);
    const extName = path.extname(input);
    const baseName = path.basename(input, extName);
    if (extName !== ".mov") {
      console.error(
        `Only support the mov file generated by the default recording software of Apple 🙆‍♂️\n${input}`
      );
      reject();
    }
    console.log(
      `File [${baseName}]Being converted.\nSize:${Number(inputFileInfo.size / 1024000).toFixed(
        2
      )}MB`
    );
    const output = path.join(inputDir, `${baseName}.gif`);
    const gif = fs.createWriteStream(output);
    gifify(input, options).pipe(gif);
    gif.on("close", () => {
      const gifInfo = fs.statSync(output);
      console.log(
        `File [${baseName}]Conversion success.\nSize:${Number(gifInfo.size / 1024000).toFixed(2)}MB`
      );
      resolve();
    });
  });
}

async function main() {
  /**
   * @param path(file/dir)
   */
  const [_p] = process.argv.slice(2);
  const sourceFilePath = path.resolve(_p);
  const isExists = fs.existsSync(sourceFilePath);

  if (!isExists) {
    console.log("The directory does not exist");
    return;
  }

  const sourceFileInfo = fs.statSync(sourceFilePath);

  if (sourceFileInfo.isFile()) {
    try {
      await convertFile(sourceFilePath);
    } catch (e) {}
  } else if (sourceFileInfo.isDirectory()) {
    const files = fs.readdirSync(sourceFilePath);
    for (let i = 0; i < files.length; i++) {
      const file = files[i];
      const filePath = path.join(sourceFilePath, file);
      if (filePath.includes("DS_Store")) continue;

      try {
        await convertFile(filePath);
      } catch (e) {}
    }

    console.log("Task finished");
  }
}

try {
  main();
} catch (e) {
  console.log(e);
}
